package com.javakc.commonutils.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = {"com.javakc.pms","com.javakc.mes"})
public class ResultAdvice implements ResponseBodyAdvice<Object> {

    private final static Logger logger= LoggerFactory.getLogger(ResultAdvice.class);

    @Value("${spring.profiles.active}")
    private String profiles;

    /**
     * 定义需要拦截的方法
     * @param methodParameter 方法参数
     * @param converterType   目标对象
     * @return  是否拦截
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        return (methodParameter.hasMethodAnnotation(ResponseBody.class)
                || AnnotatedElementUtils.hasAnnotation(methodParameter.getContainingClass(), ResponseBody.class));
    }

    /**
     * 统一封装响应返回结果
     * @param data                  返回结果
     * @param methodParameter       方法参数
     * @param mediaType             返回类型
     * @param aClass                目标对象
     * @param request               请求
     * @param response              响应
     * @return  封装结果集
     */
    @Override
    public Object beforeBodyWrite(Object data, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        if("dev".equals(profiles)) {
            String result = "";
            ObjectMapper mapper = new ObjectMapper();
            try {
                result = mapper.writeValueAsString(data);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            logger.info("=========================================");
            logger.info("执行成功,返回结果为:"+result);
            logger.info("=========================================");
        }
        if(data instanceof String)
            return data;
        if (data == null)
            return APICODE.OK();
        return APICODE.OK().data("item",data);
    }


}
